package com.suray.wcs.service.thread;


import com.suray.commin.core.utils.SpringContextHolder;
import com.suray.commin.core.utils.StringUtils;
import com.suray.system.run.ding.DingRobot;
import com.suray.wcs.res.enums.RgvStatus;
import com.suray.wcs.service.core.util.CommonUtil;
import com.suray.wcs.service.core.util.DateUtil;
import com.suray.wcs.service.enums.TaskStatusGroup;
import com.suray.wcs.service.init.SystemInit;
import com.suray.wcs.service.pojo.Rgv;
import com.suray.wcs.service.system.entity.TaskDB;
import com.suray.wcs.service.system.entity.WareHouseDB;
import com.suray.wcs.service.system.service.ITaskDBService;
import com.suray.wcs.service.system.service.IWareHouseDBService;
import com.suray.wcs.service.system.service.impl.RgvDBServiceImpl;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 任务检线程
 */

public class TaskDBRemindThread extends Thread {
    private Logger log = LoggerFactory.getLogger(TaskDBRemindThread.class);
    private final ITaskDBService taskDBService = SpringContextHolder.getBean(ITaskDBService.class);
    //超时时间配置(默认30分钟)
    public static int checkTime = 30;
    private static final IWareHouseDBService wareHouseDBService = SpringContextHolder.getBean(IWareHouseDBService.class);
    private static final RgvDBServiceImpl rgvService = SpringContextHolder.getBean(RgvDBServiceImpl.class);


    @Override
    public void run() {
        while (true) {
            getOutTimeTaskS(taskDBService, log);
            getNoOnlineRgv();
            //默认10分钟检测1次
            sleepSecond(10);
        }
    }

    public static void getOutTimeTaskS(ITaskDBService taskDBService, Logger log) {
        try {
            //查询所有未完成的  wms下发的任务  执行了但是未上报
            int allowRemind = 0;
            long checktime1 = getWareHouseTaskdbCheckTime(checkTime);
            TaskDB taskDBDemo = new TaskDB();
            taskDBDemo.setTaskStatusGroup(TaskStatusGroup.UN_FINISH.getProgressNum());
            List<TaskDB> taskListToWms = taskDBService.queryTasks(taskDBDemo);
            if (CollectionUtils.isNotEmpty(taskListToWms)) {
                //执行日期
                long newLong = System.currentTimeMillis();
                long excuteLong;
                StringBuilder stringBuilder = new StringBuilder("任务执行超过:");
                stringBuilder.append(checktime1);
                stringBuilder.append("分钟,请及时处理:\r");
                for (TaskDB taskDB : taskListToWms) {
                    excuteLong = taskDB.getCreateTime().getTime();
                    long result = (newLong - excuteLong) / (1000 * 60);
                    if (result > checktime1) {
                        allowRemind++;
                        stringBuilder.append("任务ID:" + taskDB.getTaskId() + ",任务类型:" + taskDB.getTaskType().getDescription() + ",执行时间:" + result + "分钟");
                        stringBuilder.append("\r");
                    }
                }
                stringBuilder.insert(0, "共 " + allowRemind + " 条");
                if (allowRemind > 0) {
                    //创建小铃铛信息提示
                    DingRobot.pauseMessage(stringBuilder.toString());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("任务检测异常：" + CommonUtil.toStackTrace(e));
        }
    }

    private void sleepSecond(int second) {
        try {
            TimeUnit.MINUTES.sleep(second);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static Integer getWareHouseTaskdbCheckTime(Integer checkTime) {
        WareHouseDB wareHouseDB = wareHouseDBService.getCurWareHouseDB();
        if (wareHouseDB != null && wareHouseDB.getTaskdbCheckTime() != null) {
            checkTime = wareHouseDB.getTaskdbCheckTime();
        }
        return checkTime;
    }


    /**
     * 对异常车辆进行检测
     */
    public static void getNoOnlineRgv() {
        List<Rgv> RGVS = SystemInit.RGVS;
        StringBuilder stringBuilder = new StringBuilder("离线联机车辆捕获中:");
        stringBuilder.append("\r");
        int rgv_Off_Line = 0;
        //当前检测时间
        String rgvOffLineTime = DateUtil.format(new Date(), DateUtil.YMDHMS);
        try {
            for (Rgv rgv : RGVS) {
                //联机车辆默认为正在工作，突然离线需要及时提醒工作人员离线时间和离线位置
                if (rgv.getRgvDB().getOnline() && (rgv.getRgvStatus().equals(RgvStatus.OFF_LINE))) {
                    //remak字段为离线时间，如果有离线时间，那就上报之前的之间的时间
                    String rgvRemarkTime = rgv.getRgvDB().getRemark();
                    if (StringUtils.isNotEmpty(rgvRemarkTime)) {
                        rgvOffLineTime = rgvRemarkTime;
                    } else {
                        rgvService.updateRgvRemarkOFFLineTime(rgvOffLineTime, rgv.getRgvDB().getRgvNo());
                    }
                    stringBuilder.append(rgv.getRgvDB().getRgvNo() + "号车" + "离线时间：" + rgvOffLineTime + "，所在位置：" + rgv.getRgvDB().getLocation());
                    stringBuilder.append("\r");
                    rgv_Off_Line++;
                }
            }
            stringBuilder.insert(0, "共 " + rgv_Off_Line + "辆车离线，请及时处理");
            if (rgv_Off_Line > 0) {
                //创建小铃铛信息提示
                DingRobot.pauseMessage(stringBuilder.toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
